package jnu.se.softwareengineer3306.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * @author: LovEK
 */
@Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    private final UserDetailsService userDetailsService;
    @Autowired
    SpringSecurityConfig(UserDetailsService userDetailsService){
        this.userDetailsService = userDetailsService;
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        super.configure(web);
        web.ignoring().antMatchers("/css/**","/fonts/**","images/**","/js/**");
    }

    /**
     *
     * 授权
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                // 放行登录和注册
                .antMatchers("/login","/register","/registerHandle").permitAll()
                 // 所有请求都要经过登录认证
                .anyRequest().authenticated();

        // 开启登录功能
        http.formLogin().loginPage("/login")
                .loginProcessingUrl("/login")
                .failureForwardUrl("/loginFailure")
                .successForwardUrl("/loginSuccess").permitAll();

        // 登出后返回登录页
        http.logout().logoutSuccessUrl("/login");

        // 开启记住我,关闭CSRF
        http.rememberMe()
                .and().csrf().disable();
    }

    /**
     * 认证
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
    }
}
